package com.xb.loan.cashier.biz.service.channelselect;


import com.xb.loan.cashier.biz.dao.bean.CashierPayChannelType;

import java.util.List;
import java.util.Random;

/**
 * 随机获取权重    按照支付渠道类型来获取
 */
public class RandomChannelSelector extends AbstractChannelSelector<CashierPayChannelType> {

    private final Random random = new Random();
    
    @Override
    protected CashierPayChannelType doSelect(List<CashierPayChannelType> channelTypes) {
        int length = channelTypes.size(); // 总个数
        int totalWeight = 0; // 总权重
        boolean sameWeight = true; // 权重是否都一样
        for (int i = 0; i < length; i++) {
            int weight = getWeight(channelTypes.get(i));
            totalWeight += weight; // 累计总权重
            if (sameWeight && i > 0
                    && weight != getWeight(channelTypes.get(i - 1))) {
                sameWeight = false; // 计算所有权重是否一样
            }
        }
        if (totalWeight > 0 && ! sameWeight) {
            // 如果权重不相同且权重大于0则按总权重数随机
            int offset = random.nextInt(totalWeight);
            // 并确定随机值落在哪个片断上
            for (int i = 0; i < length; i++) {
                offset -= getWeight(channelTypes.get(i));
                if (offset < 0) {
                    return channelTypes.get(i);
                }
            }
        }
        // 如果权重相同或权重为0则均等随机
        return channelTypes.get(random.nextInt(length));
    }

	@Override
	protected int getWeight(CashierPayChannelType payChannelType) {
		return 0;//payChannelType.getWeight();
	}

}
